package cn.blbsz.shop.security;

import java.util.ArrayList;
import java.util.List;

import cn.blbsz.shop.domain.p.UserEntity;
import cn.blbsz.shop.domain.p.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.blbsz.shop.domain.p.RoleEntity;
import cn.blbsz.shop.domain.s.UserBaseEntity;
import cn.blbsz.shop.domain.s.UserBaseRepository;

public class CustomerUserDetailsService implements UserDetailsService {

	@Autowired
	UserRepository userRepository;

	@Override
	public UserDetails loadUserByUsername(String tel) throws UsernameNotFoundException {
		// 根据用户名到数据库查询是否有这个用户
		UserEntity userEntity = userRepository.findByTel(tel);
		if (userEntity == null) {
			throw new UsernameNotFoundException("not found");
		}

		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		List<RoleEntity> roleEntities = userEntity.getRoleEntities();
		
		for (RoleEntity roleEntity : roleEntities) {
			 authorities.add(new SimpleGrantedAuthority(roleEntity.getName()));
		}
       
        return new UserDetail(userEntity, authorities);

	}

}
